<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * Class of form to send new mail
 *
 * @package   block_email_list
 * @author    Toni Mas <toni.mas@uib.dot.es>
 * @copyright 2006 by <toni.mas at uib dot es>
 * @license   The source code packaged with this file is Free Software, Copyright (C) 2006 by
 *            <toni.mas at uib dot es>.
 *            It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
 *            You can get copies of the licenses here: http://www.affero.org/oagpl.html
 *            AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".
 * @uses $CFG
 */
global $CFG;

require_once($CFG->dirroot.'/lib/formslib.php');
require_once($CFG->dirroot.'/lib/uploadlib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/lib.php');
require_once($CFG->dirroot.'/blocks/email_list/email/email.class.php');

/**
 * A mail edit form
 *
 * @copyright 2006 by <toni.mas at uib dot es>
 * @license   http://www.affero.org/oagpl.html AFFERO GENERAL PUBLIC LICENSE
 */
class mail_edit_form extends moodleform {

    /**
     * Add a recipient block to the page
     *
     * @param string $type The type of the block.  Should be either 'to', 'cc', or 'bcc'
     * @return void
     * @uses $CFG
     */
    function add_recipient_block($type = 'to') {
        global $CFG;

        $mform =& $this->_form;
        $string = get_string($type, 'block_email_list');

        $email_enable_ajax = isset($CFG->email_enable_ajax) ? $CFG->email_enable_ajax : 0;

        if ($email_enable_ajax) {

            $mform->addElement('html', '<div class="mform fitemtitle">'. $string .'</div>');
            // Add div html element
            $mform->addElement('html', '<div class="ajax_selected_participants">');

            // Added to allow for YUI autocomplete styling
            $mform->addElement('html', '<div class="yui-skin-sam">');

            $mform->addElement('html', '<div class="fitem">'
                  .' <div class="ajaxfelement ftext"><input size="5" '
                  .     'class="ajax_textareacontacts" name="name'. $type .'" id="id_name'. $type
                  .     '" type="text" /><span></span></div></div>'
                  . '<div class="ajaxfelement fstatic yui-ac">'
                  . '<div class="yui-ac-container" id="qResults'. $string .'"></div></div>&nbsp;');

            // Change textarea to text.
            //$mform->addElement('text', 'name'. $type, '', array('size'=>'5', 'class'=>'ajax_textareacontacts'));

            // Stores the YUI autocomplete results
             //$mform->addElement('static', 'qResults'. $string, '', '<div id="qResults'. $string .'"></div>');
             $mform->addElement('html', '</div>');

             // Close div html element
             $mform->addElement('html', '</div>');

        } else {
            $mform->addElement('textarea', 'name'. $type, $string,
                array('rows'=> '2', 'cols'=>'65', 'class'=>'textareacontacts', 'disabled'=>'true'));
            $mform->setType('name'. $type, PARAM_TEXT);
        }
    }

    /**
     * Define the form
     *
     * @uses $CFG
     * @uses $COURSE
     * @return void
     */
    function definition() {
        global $CFG, $COURSE, $PAGE, $DB;

        // Get customdata
        $oldmail          = $this->_customdata['oldmail'];
        $action           = $this->_customdata['action'];

        $mform =& $this->_form;

        /// Print the required moodle fields first
        $mform->addElement('header', 'moodle', get_string('mail', 'block_email_list'));

        $email_enable_ajax = isset($CFG->email_enable_ajax) ? $CFG->email_enable_ajax : 0;

        // Check if there will be any contacts showing up for this course
        $courseid = optional_param('course', 0, PARAM_INT);
        if ($course = $DB->get_record('course', array('id' => $courseid)) && $courseid > 1) {
            $sitecontext = context_system::instance();
            $frontpagectx = context_course::instance(SITEID);

            list($roles, $avoidroles) = get_mailable_roles($PAGE->context);
            $values = array();

            if ($usercontexts = get_parent_contexts($PAGE->context)) {
                $listofcontexts = '('.implode(',', $usercontexts).')';
            } else {
                $listofcontexts = '('.$sitecontext->id.')'; // must be site
            }

            $from = ' FROM {user} u'
                   .' LEFT OUTER JOIN {context} ctx'
                   .' ON (u.id=ctx.instanceid AND ctx.contextlevel = '.CONTEXT_USER.') ';

            if ($PAGE->context->id != $frontpagectx->id) {
                $from  .= ' JOIN {role_assignments} r'
                       .' ON u.id=r.userid'
                       .' LEFT OUTER JOIN {user_lastaccess} ul'
                       .' ON (r.userid=ul.userid and ul.courseid = ?) ';
                $values[] = $courseid;
            }

            $values[] = 0;
            $values[] = 'guest';
            $where  = ' WHERE u.deleted=? AND u.username != ?';

            if ($PAGE->context->id != $frontpagectx->id) {
                list($clsql, $params) = $DB->get_in_or_equal($listofcontexts);
                $where .= " AND (r.contextid = ? OR r.contextid $clsql)";
                $values[] = $PAGE->context->id;
                $values = array_merge($values, $params);
            }

            if ($PAGE->context->id != $frontpagectx->id) {
                $where .= ' AND (ul.courseid = ? OR ul.courseid IS NULL)';
                $values[] = $courseid;
                if (sizeof($avoidroles) > 0) {
                    list($arsql, $params) = $DB->get_in_or_equal($avoidroles, SQL_PARAMS_QM, '', false);
                    $where .= ' AND r.roleid '. $arsql;
                    $values = array_merge($values, $params);
                }
            }

            $totalcount = $DB->count_records_sql('SELECT COUNT(distinct u.id) '.$from.$where, $values);
        } else {
            $totalcount = 0;
        }

        if (!$totalcount) {
            $mform->addElement('html', '<div align="center">'.get_string('nocontacts', 'block_email_list').'</div>');
        } else {
            if (! $email_enable_ajax) {
                $mform->addElement('button', 'urlcc', get_string('participants', 'block_email_list').'...',
                        array('onclick' => 'this.target=\'participants\'; return openpopup(true,'
                                          ." {url:'/blocks/email_list/email/participants.php?id={$COURSE->id}',"
                                          .' name:\'participants\', options:\'menubar=0,location=0,scrollbars=1,'
                                          . 'resizable,width=760,height=700\', fullscreen:0});' ));
            }

            // Mail to
            $this->add_recipient_block('to');

            // Mail cc
            $this->add_recipient_block('cc');

            // Mail bcc
            $this->add_recipient_block('bcc');
        }

        if (empty($CFG->noemailever) && !empty($CFG->email_enable_external_address)) {
            $mform->addElement('text', 'toext', get_string('toexternaladdr', 'block_email_list'),
                               'class="emailexternal" maxlength="255" size="60"');
            $mform->setType('toext', PARAM_TEXT);
            // add help button - somehow move to end of field?
            $mform->addHelpButton('toext', 'emailexternal', 'block_email_list');
        }

        $mform->addElement('text', 'subject', get_string('subject', 'block_email_list'),
                           'class="emailsubject" maxlength="254" size="60"');
        $mform->setDefault('subject', '');
        $mform->addRule('subject', get_string('nosubject', 'block_email_list'), 'required', null, 'client');
        $mform->setType('subject', PARAM_TEXT);

        $sattach = get_string('attachment', 'block_email_list');

        // Add old attachments
        if (isset($oldmail->id) && ($oldmail->id > 0)) {
            $email = new eMail();
            $email->set_email($oldmail);

            if ($email->has_attachments()) {

                // Get mail attachments
                $attachments = $email->get_attachments();

                if ($attachments) {
                    $i = 0;

                    foreach ($attachments as $attachment) {
                        $mform->addElement('checkbox', 'oldattachment'.$i.'ck', $sattach, $attachment->name);
                        $mform->setType('oldattachment'.$i.'ck', PARAM_BOOL);
                        $mform->setDefault('oldattachment'.$i.'ck', true);
                        $mform->addElement('hidden', 'oldattachment'.$i, "$attachment->path$attachment->name");
                        $mform->setType('oldattachment'.$i, PARAM_SAFEPATH);
                        $i++;
                    }
                }
            }
        }

        // Upload files
        $options = array('maxbytes' => $COURSE->maxbytes, 'subdirs'  => 0, 'maxfiles' => 50);

        $mform->addElement('filemanager', 'attachments', $sattach, null, $options);

         // Patch. Thanks
        /// TODO: Add all inputs files who added by user
        foreach ($_FILES as $key=>$value) {

            if (substr($key, 0, strlen($key)-1) == 'FILE_' && !$mform->elementExists($key)) {
                $mform->addElement('file', $key, '', 'value="'.$value.'"');
            }
        }

        $mform->addElement('htmleditor', 'body', get_string('body', 'block_email_list'),
                           array('rows'=> '25', 'cols'=>'65'));
        $mform->setDefault('body', '');
        $mform->setType('body', PARAM_RAW);

        /// Add some extra hidden fields
        if ( isset($oldmail->id) ) {
            $mform->addElement('hidden', 'id', $oldmail->id);
        } else {
            $mform->addElement('hidden', 'id');
        }
        $mform->setType('id', PARAM_INT);
        $mform->addElement('hidden', 'course', $COURSE->id);
        $mform->setType('course', PARAM_INT);
        $mform->addElement('hidden', 'action', $action);
        $mform->setType('action', PARAM_ALPHANUM);
        $mform->addElement('hidden', 'to');
        $mform->setType('to', PARAM_TEXT);
        $mform->addElement('hidden', 'cc');
        $mform->setType('cc', PARAM_TEXT);
        $mform->addElement('hidden', 'bcc');
        $mform->setType('bcc', PARAM_TEXT);
        $mform->addElement('hidden', 'respondedid', isset($email->respondedid) ? $email->respondedid : 0);
        $mform->setType('respondedid', PARAM_INT);

        if (isset($oldmail->id) ) {
            $mform->addElement('hidden', 'oldmailid', $oldmail->id);
        }

        // Add 3 buttons (Send, Draft, Cancel)
        $buttonarray=array();
        $buttonarray[] = &$mform->createElement('submit', 'send', get_string('send', 'block_email_list'));

        $buttonarray[] = &$mform->createElement('submit', 'draft', get_string('savedraft', 'block_email_list'));
        $buttonarray[] = &$mform->createElement('cancel');
        $mform->addGroup($buttonarray, 'buttonar', '', array(' '), false);
        $mform->closeHeaderBefore('buttonar');

        if (empty($CFG->noemailever) && !empty($CFG->email_enable_external_address)) {
            // add submit/send onclick handler
            $mform->addElement('html', "\n<script type=\"text/javascript\">\n//<![CDATA[\n".
                "  document.getElementById('id_send').onclick=function() {\n".
                " return (document.sendmail.toext.value == '' || confirm('".
                get_string('suretosendext', 'block_email_list')."')) ? true: false;\n };\n//]]>\n</script>\n");
        }
    }


    /**
     * Validation
     *
     * @param array $data The data to validate
     * @return bool/array Either true or an array of errors
     */
    function validation($data, $files = array()) {
        $error = array();

        // Get form
        $mform    =& $this->_form;

        if (! (isset($data['to']) || isset($data['cc']) || isset($data['bcc'])) && empty($data['draft'])) {
            $error['nameto'] = get_string('nosenders', 'block_email_list');
            $error['namecc'] = get_string('nosenders', 'block_email_list');
            $error['namebcc'] = get_string('nosenders', 'block_email_list');
        }


        /// TODO: Add all inputs files who added by user
        foreach ($_FILES as $key=>$value) {

            if (substr($key, 0, strlen($key)-1) == 'FILE_' && !$mform->elementExists($key)) {
                $mform->addElement('file', $key, '', 'value="'.$value.'"');
            }
        }
        return (count($error)==0) ? true : $error;
    }
}
